<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use DB;
use Crypt;


class LoginController extends Controller
{
    //
    public function login(Request $request)
    {

        if($request -> isMethod('POST'))
        {  
            // $isLogin = \Cookie::get('isLogin');
            // if($isLogin)
            // {
            //     $res = DB::table('users') -> where('email',$isLogin) -> first(); 
            //     Session::put('master',$res);
            //     return redirect('/') -> with(['info' => '登录成功']);
            // }

            //闪存
            $request -> flashOnly('email');
          
            //验证码匹配
            // $code = $request -> input('code');
            // if($code != Session::get('code'))
            // {
            //     return back() -> with(['info' => '验证码错误']);
            // }
            //验证邮箱和密码
            $email = $request -> input('email');
            $res = DB::table('users') -> where('email',$email) -> first();
            if(!$res)
            {
                return back() -> with(['info' => '用户未注册']);
            }
            //解密
            $password = Crypt::decryptString($res -> password);
            if($request -> input('password') != $password )
            {
                return back() ->with(['info' => '用户或者密码错误']);
            }
            //判断是否记住我
            // if($request -> has('checkMe'))
            // {
            //    \Cookie::queue('isLogin',$res -> email,60 * 24 * 7);
            // } 
            Session::put('master',$res);
            if(session('cart_flag')){
                
                return redirect('/home/cart/index') -> with(['info' => '购物车']);
            }
            return redirect('/') -> with(['info' => '登录成功']);
        }else
        {   

            return view('home.login.index',['title' => '登录']);
        }
       
    }
    public function cart_login()
    {

    }

    public function logout(Request $request)
    {
        $res = Session::forget('master');
        $res2 = Session::forget('cart');
        
        if(!$res && !$res2)
        {
            return redirect('/home/index') -> with(['info' => '退出成功']);
        }else
        {
            return back() -> with(['info' => '退出失败']);
        }
      

    }
}
